<template>
  <div class="main">
    <div class="viator">
      <el-avatar
        shape="circle"
        :size="100"
        src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
      ></el-avatar>
      <el-upload>
        <el-button type="primary">上传头像</el-button>
      </el-upload>
    </div>
    <div class="form">
      <el-form
        ref="resetFormRef"
        style="width: 300px; margin: auto"
        :model="resetForm"
        status-icon
        :rules="rules"
        label-width="120px"
        class="demo- resetForm"
      >
        <el-form-item label="User:" prop="adminAccount">
          <el-input
            v-model="resetForm.adminAccount"
            type="input"
            autocomplete="on"
          />
        </el-form-item>
        <el-form-item label="Email:" prop="email">
          <el-input v-model="resetForm.email" type="email" autocomplete="on" />
        </el-form-item>
        <el-form-item label="旧密码:" prop="password">
          <el-input
            v-model="resetForm.password"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="新密码:" prop="password2">
          <el-input
            v-model="resetForm.password2"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="确认密码:" prop="password3" width="100px">
          <el-input
            v-model="resetForm.password3"
            type="password"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item style="margin: auto">
          <el-button type="primary" @click="submitForm(resetFormRef)"
            >提交</el-button
          >
          <el-button @click="resetForm1(resetFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <!-- autocomplete属性表示表单是否自动填充（on，off） -->
</template>

<script lang="ts">
import { reactive, ref, toRefs } from "vue";
import type { FormInstance } from "element-plus";
import { isEmail } from "./utils/email";
import { ElMessage } from "element-plus";
import router from "../../router";
import type { UploadProps, UploadUserFile } from "element-plus";
import { updatePassWord } from "../../http/api";
import { formData } from "../../type/upData";
export default {
  setup() {
    const data = reactive(new formData());

    const fileList = ref<UploadUserFile[]>([
      {
        name: "element-plus-logo.svg",
        url: "https://element-plus.org/images/element-plus-logo.svg",
      },
      {
        name: "element-plus-logo2.svg",
        url: "https://element-plus.org/images/element-plus-logo.svg",
      },
    ]);

    const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
      console.log(file, uploadFiles);
    };

    const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
      console.log(uploadFile);
    };

    const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
      ElMessage.warning(
        `The limit is 3, you selected ${
          files.length
        } files this time, add up to ${
          files.length + uploadFiles.length
        } totally`
      );
    };

    const imageUrl = ref("");

    const handleAvatarSuccess: UploadProps["onSuccess"] = (
      response,
      uploadFile
    ) => {
      imageUrl.value = URL.createObjectURL(uploadFile.raw!);
    };

    const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
      if (rawFile.type !== "image/jpeg") {
        ElMessage.error("Avatar picture must be JPG format!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      }
      return true;
    };

    //旧密码
    const validatePass1 = (rule: any, value: any, callback: any) => {
      if (value === "") {
        callback(new Error("请输入旧密码"));
      } else {
        if (data.resetForm.password !== "") {
          if (!resetFormRef.value) return;
          resetFormRef.value.validateField("password", () => null);
        }
        callback();
      }
    };
    //新旧密码不能相同
    const validatePass = (rule: any, value: any, callback: any) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value == data.resetForm.password) {
        callback(new Error("新密码和旧密码不能相同"));
      } else {
        callback();
      }
    };
    // 确认密码时和新密码进行比较
    const validatePass2 = (rule: any, value: any, callback: any) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== data.resetForm.password2) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    //邮箱正則验证
    const validateEmail = (rule: any, value: any, callback: any) => {
      //isEmail是定义的一个正则
      if (!isEmail(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };
    const rules = reactive({
      adminAccount: [{ trigger: "blur", required: true }],
      email: [{ validator: validateEmail, trigger: "blur", required: false }],
      password: [{ validator: validatePass1, trigger: "blur", required: true }], //旧密码
      password2: [{ validator: validatePass, trigger: "blur", required: true }], //新密码
      password3: [
        { validator: validatePass2, trigger: "blur", required: true },
      ],
    });
    const resetFormRef = ref<FormInstance>();
    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          updatePassWord(data.resetForm).then((res: any) => {
            if (res.code == 0) {
              localStorage.removeItem("token");
              router.push("/login");
              ElMessage({
                message: "修改成功,请重新登录！",
                type: "success",
              });
            } else {
              ElMessage({
                message: res.msg,
                type: "error",
              });
            }
          });
        } else {
          ElMessage({
            message: "请正确填写表单",
            type: "warning",
          });
          return false;
        }
      });
    };
    const resetForm1 = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };
    return {
      ...toRefs(data),
      rules,
      submitForm,
      resetFormRef,
      resetForm1,
    };
  },
};
</script>
<style scoped>
.main {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.viator {
  margin-left: 100px;
}
</style>
